package com.module.content.ui.info

import android.view.View
import android.widget.FrameLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.allen.app.data.bean.FRAGMENT_ID_INFO
import com.allen.app.data.bean.Info
import com.allen.app.data.bean.InfoBean
import com.allen.app.data.event.EndHomeAnimEvent
import com.allen.app.data.event.InfoGifPlayEvent
import com.allen.app.helper.AutoPlayVideoHandler
import com.allen.app.helper.launchInfoDetailsActivity
import com.allen.base.base.fragment.BaseRecyclerFragment
import com.allen.base.base.recycler.decorate.DividerItemDecoration
import com.allen.base.utils.AppUtils
import com.allen.base.utils.ViewUtils
import com.hwangjr.rxbus.RxBus
import com.hwangjr.rxbus.annotation.Subscribe
import com.hwangjr.rxbus.thread.EventThread
import com.module.content.R
import com.module.content.ui.info.adapter.InfoAdapter
import com.module.content.ui.info.adapter.InfoImageItemAdapter

/**
 * author : Allen
 * date   : 2020/08/10
 * time   : 17:02
 * desc   : 糗事主页列表
 */
class InfoFragment : BaseRecyclerFragment<InfoViewModel, Info, InfoBean>(),
    AutoPlayVideoHandler.AutoPlayVideoHandlerListener {

    companion object {
        fun newInstance(tag: Int): InfoFragment {
            val fragment = InfoFragment()
            fragment.tag = tag
            return fragment
        }
    }

    var tag = 0
    override fun getAdapter() = InfoAdapter()
    override fun getListTag(): Int = tag
    override fun isRegisterRxBus(): Boolean = true
    override fun getItemDivider() = DividerItemDecoration(
        AppUtils.getColor(R.color.color_FAFAFA),
        ViewUtils.dp2px(1),
        ViewUtils.dp2px(16),
        ViewUtils.dp2px(16)
    )

    private var autoPlayVideoHandler: AutoPlayVideoHandler? = null

    //当前播放列表的下标
    private var playIndex = 0

    //当前播放列表的控件
    private var itemView: View? = null

    //当前播放GIF的下标
    private var gifIndex = -1

    override fun initView() {
        super.initView()
        val layoutManager = getRecyclerView()?.getLayoutManager()
        if (layoutManager is LinearLayoutManager) {
            autoPlayVideoHandler =
                AutoPlayVideoHandler(layoutManager, mAdapter?.headerLayoutCount ?: 0, this)
        }
    }

    override fun initEvents() {
        mAdapter?.setOnItemClickListener { adapter, _, position ->
            val data = adapter.getItem(position)
            if (data is InfoBean) {
                launchInfoDetailsActivity(data.user?.login)
            }
        }
        val recyclerView = getRecyclerView()?.getRecyclerView()
        recyclerView?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                autoPlayVideoHandler?.onScrollStateChanged(newState)
            }
        })
        recyclerView?.addOnChildAttachStateChangeListener(object :
            RecyclerView.OnChildAttachStateChangeListener {
            override fun onChildViewAttachedToWindow(view: View) {
            }

            override fun onChildViewDetachedFromWindow(view: View) {
                (mAdapter as? InfoAdapter)?.getVideoProvider()?.onChildViewDetachedFromWindow(view)
                getInfoImageItemAdapter()?.onChildViewDetachedFromWindow(view)
            }
        })
    }


    fun autoPlay() {
        if (isCurrentPage()) {
            autoPlayVideoHandler?.sendAutoPlayMessage()
        }
    }

    fun autoStop() {
        (mAdapter as? InfoAdapter)?.getVideoProvider()?.stop()
        getInfoImageItemAdapter()?.stop()
    }

    override fun loadFinish() {
        RxBus.get().post(EndHomeAnimEvent(FRAGMENT_ID_INFO))
        autoPlay()
    }

    override fun onAutoPlayVideoHandlerGetMediaPath(index: Int): String? {
        if (index >= 0 && index < mAdapter?.data?.size ?: 0) {
            val data = mAdapter?.getItem(index)
            return if (data?.format == "multi") {
                getGifUrl(data)
            } else {
                data?.origin_url
            }
        }
        return null
    }

    private fun getGifUrl(data: InfoBean): String? {
        if (!data.attachments.isNullOrEmpty()) {
            val size = (data.attachments?.size ?: 0) - 1
            if (gifIndex >= size) {
                gifIndex = -1
            }
            var hasGif = false
            data.attachments?.forEachIndexed { ind, item ->
                if (item.format == "gif") {
                    hasGif = true
                    if (ind > gifIndex) {
                        gifIndex = ind
                        return item.low_url
                    }
                } else if (size == ind && hasGif) {
                    gifIndex = size
                    return getGifUrl(data)
                }
            }
        }
        return null
    }

    override fun onAutoPlayVideoHandlerAdapterPlay(index: Int, itemView: View?) {
        if (playIndex != index) {
            gifIndex = -1
        }
        this.itemView = itemView
        val data = mAdapter?.data
        if (data != null && index < data.size) {
            val item = data[index]
            if (item.format == "video") {
                (mAdapter as? InfoAdapter)?.getVideoProvider()?.setVideoPlayer(
                    itemView?.findViewById(R.id.contentLayout), data[index].low_url, index
                )
            } else if (item.format == "multi") {
                playGifVideo(index)
            }
        }
        playIndex = index
    }

    private fun playGifVideo(index: Int) {
        val data = mAdapter?.data
        if (data != null && index < data.size) {
            val item = data[index]
            val url = getGifUrl(item)
            val imageRecyclerView = itemView?.findViewById<RecyclerView>(R.id.imageRecyclerView)
            val listCount = imageRecyclerView?.childCount ?: 0
            if (listCount > 0 && gifIndex < listCount && gifIndex >= 0) {
                val childView = imageRecyclerView?.getChildAt(gifIndex)
                val contentLayout = childView?.findViewById<FrameLayout>(R.id.contentLayout)
                getInfoImageItemAdapter()?.setVideoPlayer(contentLayout, url, gifIndex)
            }
        }
    }

    private fun getInfoImageItemAdapter(): InfoImageItemAdapter? {
        val imageRecyclerView = itemView?.findViewById<RecyclerView>(R.id.imageRecyclerView)
        val listCount = imageRecyclerView?.childCount ?: 0
        if (listCount > 0 && gifIndex < listCount && gifIndex >= 0) {
            val adapter = imageRecyclerView?.adapter
            if (adapter is InfoImageItemAdapter) {
                return adapter
            }
        }
        return null
    }


    @Subscribe(thread = EventThread.MAIN_THREAD)
    fun onMessageEvent(messageEvent: InfoGifPlayEvent) {
        if (isCurrentPage()) {
            gifIndex = messageEvent.position
            playGifVideo(playIndex)
        }
    }

    /**
     * 判断是否是当前页面
     */
    private fun isCurrentPage(): Boolean {
        return InfoFragmentIndex.currentIndex == tag
    }
}